package com.uyii.springbootredis.service;

import com.uyii.springbootredis.dto.SearchDto;
import io.redisearch.client.Client;
import io.redisearch.Document;
import io.redisearch.Query;
import io.redisearch.Schema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class RedisearchService {

    private final Client redisearchClient;

    @Autowired
    public RedisearchService(JedisPool jedisPool) {
        this.redisearchClient = new Client("indexName", jedisPool);
    }

    public void createIndex() {
        // Create an index with a text field
        Schema schema = new Schema()
                .addTextField("title", 5.0)
                .addTextField("content", 1.0);
        Client.IndexOptions options = Client.IndexOptions.defaultOptions();
        redisearchClient.createIndex(schema, options);
    }

    public void addDocument(SearchDto dto) {
        Map<String, Object> fields = new HashMap<>();
        fields.put("title", dto.getTitle());
        fields.put("content", dto.getContent());

        // redis key
        String uuid = UUID.randomUUID().toString();
        String key = "article:" + uuid;

        redisearchClient.addDocument(key, fields);
    }

    public List<Document> search(String keyword) {
        // 创建查询字符串，分别为title和content添加通配符
        String querystr = "(@title:" + keyword + "* | @content:" + keyword + "*)";
        Query query = new Query(querystr);

        return redisearchClient.search(query).docs;
    }
}